package com.softeem.idriveserver.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.idriveserver.dto.Result;
import com.softeem.idriveserver.entity.VehicleInfo;
import com.softeem.idriveserver.service.VehicleInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 车辆信息管理接口
 */
@RestController
public class VehicleInfoController {

    @Autowired
    private VehicleInfoService vehicleInfoService;

    /**
     * 车辆信息添加
     */
    public Result add(VehicleInfo vehicleInfo) {
        //根据车辆vin码查询
        VehicleInfo vehicle = vehicleInfoService.getOne(Wrappers.lambdaQuery(VehicleInfo.class).eq(VehicleInfo::getVin, vehicleInfo.getVin()));
        if(vehicle != null){
            return Result.error().setMsg("车辆已存在,vin重复");
        }
        boolean b = vehicleInfoService.save(vehicleInfo);
        return b ? Result.ok().setMsg("添加成功") : Result.error().setMsg("添加失败");
    }

    /**
     * 分页查询车辆信息
     */
    public Result list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "2") Integer limit) {
        List<VehicleInfo> list = vehicleInfoService.list(new Page<>(page, limit));
        return Result.ok().setData(list);
    }

    /**
     * 根据id查询车辆
     */
    public Result getById(Integer id) {
        VehicleInfo vehicleInfo = vehicleInfoService.getById(id);
        return Result.ok().setData(vehicleInfo);
    }

    /**
     * 根据vin码查询车辆
     */
    public Result getByVin(String vin) {
        VehicleInfo vehicleInfo = vehicleInfoService.getOne(Wrappers.lambdaQuery(VehicleInfo.class).eq(VehicleInfo::getVin, vin));
        return Result.ok().setData(vehicleInfo);
    }

    /**
     * 删除车辆信息
     */
    public Result delete(Integer id) {
        boolean b = vehicleInfoService.removeById(id);
        return b ? Result.ok().setMsg("删除成功") : Result.error().setMsg("删除失败");
    }

    /**
     * 修改车辆信息
     */
    public Result modify(VehicleInfo vehicleInfo) {
        return vehicleInfoService.updateById(vehicleInfo) ? Result.ok().setMsg("修改成功") : Result.error().setMsg("修改失败");
    }

}
